#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>

#include "Log.hpp"

using namespace log_ns;

const static std::string sep = ": ";

class Dict
{
    void LoadDict(const std::string& path)
    {
        // ifstream:只用于写入， in:文件流对象
        std::ifstream in(path);
        if (!in.is_open())
        {
            LOG(FATAL, "open file %s failed!\n", path.c_str());
            exit(1);
        }
        LOG(INFO, "open file success!\n");

        std::string line;
        while (std::getline(in, line))
        {
            LOG(DEBUG, "load info:[%s] success!", line.c_str());

            if (line.empty())
                continue;

            auto pos = line.find(sep);
            if (pos == std::string::npos) // 空行
                continue;

            std::string key = line.substr(0, pos);
            if (key.empty())
                continue;

            std::string value = line.substr(pos + sep.size());
            if (value.empty())
                continue;

            //_dict.insert({key, value});
            _dict.insert(std::make_pair(key, value));
        }
        LOG(INFO, "LoadDict success!\n");

        in.close();
    }

public:
    Dict(std::string path) : _path(path)
    {
        // 加载文件内容
        LoadDict(path);
    }

    std::string Translate(std::string word)
    {
        if(word.empty()) return "empty None";
        auto iter = _dict.find(word);
        if (iter == _dict.end())
            return "end None";
        else
            return iter->second;
    }

    ~Dict()
    {
    }

private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _path;
};